# -*- coding: utf-8 -*-
# @Author: gdf
# @Date: 2025-01-04
# @Last Modified by: gdf
# @Last Modified time: 2024-01-04

# @Description: generate a new collection name by id
import uuid
from datetime import datetime

def generate_collection_name(coll_name:str,coll_id:[int,None]=None):
    try:
        # Ensure the id is a positive integer
        # if not isinstance(coll_id, int) or coll_id < 0:
        #     raise ValueError("The ID must be a positive integer.")

        # Get today's date in YYYYMMDD format
        date_str = datetime.now().strftime('%Y%m%d')

        # Convert id to string and strip leading zeros; this step is no longer necessary for the final name
        # coll_id_str = str(coll_id).lstrip('0')
        # Validate and process coll_name
        if not coll_name:
            raise ValueError("The collection name must not be empty.")
        
        # Replace non-alphanumeric characters and spaces with underscores
        processed_coll_name = ''.join(c if c.isalnum() else '_' for c in coll_name)
        
        # Truncate to 100 characters if necessary
        if len(processed_coll_name) > 100:
            processed_coll_name = processed_coll_name[:100]


        # Generate a random UUID and take the first 8 characters as the random part
        random_part = uuid.uuid4().hex[:4]

        # Define the prefix for the collection name, customizable
        prefix = "cp"

        # Construct the final collection name with the new order: prefix_random_part_date_str
        collection_name = f"{prefix}_{processed_coll_name}_{date_str}{random_part}"

        return collection_name

    except ValueError as ve:
        # Handle errors related to value validation
        print(f"ValueError: {ve}")
        raise
    except Exception as e:
        # Handle any other unexpected exceptions
        print(f"An unexpected error occurred: {e}")
        raise

